import 'dart:typed_data'; // 强制使用标准库的 Uint8List
import 'package:bip39/bip39.dart' as bip39;
import 'package:bip32/bip32.dart' as bip32;
import 'package:hex/hex.dart';
import 'package:web3dart/credentials.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class WalletSDK {
  // 单例模式
  static final WalletSDK _instance = WalletSDK._internal();
  factory WalletSDK() => _instance;
  WalletSDK._internal();
  // 安全存储实例
  final _storage = const FlutterSecureStorage();
  
  // 存储键名
  static const _mnemonicKey = 'wallet_mnemonic';
  static const _privateKeyKey = 'wallet_private_key';
  static const _addressKey = 'wallet_address';

  // 生成助记词
  String generateMnemonic() {
    return bip39.generateMnemonic();
  }

  // 从助记词生成以太坊私钥（完全兼容 MetaMask）
  String generateEthereumPrivateKey(String mnemonic) {
    print('开始生成私钥...');
    print('助记词: $mnemonic');
    
    // 1. 从助记词生成种子
    final seed = bip39.mnemonicToSeed(mnemonic);
    final seedHex = bip39.mnemonicToSeedHex(mnemonic);
    print('种子: $seedHex');
    
    // 2. 生成主私钥
    final masterKey = bip32.BIP32.fromSeed(seed);
    print('主私钥: ${HEX.encode(masterKey.privateKey?.toList() ?? [])}');
    print('主链码: ${HEX.encode(masterKey.chainCode)}');
    
    // 3. 派生以太坊私钥
    final path = "m/44'/60'/0'/0/0";
    print('派生路径: $path');
    
    final childKey = masterKey.derivePath(path);
    if (childKey.privateKey == null) {
      throw Exception('无法派生私钥');
    }
    
    // 4. 转换为十六进制字符串
    final privateKeyHex = HEX.encode(childKey.privateKey!.toList());
    print('最终私钥: $privateKeyHex');
    
    return '0x$privateKeyHex';
  }

  // 验证助记词是否有效
  bool validateMnemonic(String mnemonic) {
    return bip39.validateMnemonic(mnemonic);
  }

  // 保存钱包数据
  Future<void> saveWalletData({
    required String mnemonic,
    required String privateKey,
    required String address,
  }) async {
    await Future.wait([
      _storage.write(key: _mnemonicKey, value: mnemonic),
      _storage.write(key: _privateKeyKey, value: privateKey),
      _storage.write(key: _addressKey, value: address),
    ]);
  }

  // 获取钱包数据
  Future<Map<String, String?>> getWalletData() async {
    final data = await Future.wait([
      _storage.read(key: _mnemonicKey),
      _storage.read(key: _privateKeyKey),
      _storage.read(key: _addressKey),
    ]);
    return {
      'mnemonic': data[0],
      'privateKey': data[1],
      'address': data[2],
    };
  }

  // 检查钱包是否存在
  Future<bool> hasWallet() async {
    final mnemonic = await _storage.read(key: _mnemonicKey);
    return mnemonic != null;
  }

  // 清除钱包数据
  Future<void> clearWalletData() async {
    await Future.wait([
      _storage.delete(key: _mnemonicKey),
      _storage.delete(key: _privateKeyKey),
      _storage.delete(key: _addressKey),
    ]);
  }

  //获取地址
  String getAccountAddress(String privateKeyHex) {
    //这里后面可能还要区分以太坊地址 波场链地址  sonala地址等 这个类应该相当于sdk不做具体逻辑处理
    final privateKey = EthPrivateKey.fromHex(privateKeyHex);
    final address = privateKey.address;
    return address.hexEip55; // 符合 EIP-55 校验的地址
  }
}